import { ref, reactive, onMounted, computed, defineEmits, watch, getCurrentInstance } from 'vue';
import useUserStore from '@/store/modules/user';
import ContextMenu from '@imengyu/vue3-context-menu';
import { ApiPerTreeNodeAll } from '@/api/personDoc/personDocApi';
import {
  apiTreeFileSelectTree,
  apiTreeFileSelectTreeAddFolder,
  apieEnterpriseFilesTreeQueryPaging,
  apiRecycleBinRemoveFile,
  apiFilesCollectionAddCollection,
  apifilesCollectionCancelCollection,
  apiFileAttentionAddAttention,
  apiFileAttentionCancelAttention,
  apiEnterpriseFilesTreeTop,
  apiEnterpriseFilesTreeRename,
  apiEnterpriseFilesTreeUpdateAiFiles,
  apiEnterpriseFilesTreeToDify
} from '@/api/enterpriseDoc/enterpriseDocApi';
import {
  apiOnlinePrint
} from '@/api/personDoc/personDocApi';
import printJS from 'print-js';
import { enterpriseRole } from '@/store/modules/enterpriseRole';
const roleStore = enterpriseRole();
export default function docMixins(configs: any) {
  const { proxy } = getCurrentInstance() as any;
  const { pageType, requstApi, rowData } = configs;
  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  /**文件树参数---------------start */
  const headNodeId = ref('');
  const treeLoading = ref(false);
  const treeDocumentRefs: any = ref();
  const multipleTable = ref(null);
  const managementList = ref([]);
  const defaultProps: any = {
    //树
    children: 'children',
    label: 'realName',
    isLeaf: 'leaf'
  };
  const currentId = ref(0);
  const expandedKeys = ref([]);
  watch(currentId, (newVal) => {
    // 设置树高亮部分
    if (newVal !== null && newVal !== undefined) {
      (treeDocumentRefs.value as any).setCurrentKey(newVal);
    } else {
      (treeDocumentRefs.value as any).setCurrentKey(null);
    }
  });
  const treeRequestParams = ref({
    sort: ['sort Asc', 'type Desc', 'real_name ASC']
  });
  const rightInfoArray = ref([]);
  const teamId = ref(null);
  const tableRowArray = ref([]); //选中的表格数据
  /**文件树参数---------------end */
  /**面包屑参数---------------start */
  const breadList = ref([]);
  const stratBreadList = ref([]);
  /**面包屑参数---------------end */
  /**搜索----start */
  const searchInfoObj = ref({}); //保存搜索出来单击了的数据,用于高亮这一行
  const searchTableDataClone = ref([]);
  /**搜索----end */
  /**表格分页---start */
  const isTableHeaderBtn = ref(false); //是否隐藏表格头
  const tableHeight = ref(0);
  const tableData = ref([]);
  const previewTableDataClone = ref([]);
  const tableRequestParams: any = ref({
    page: 0,
    size: 40,
    parentId: 0,
    pageCount: 1
  });
  const tableLoading = ref(false);
  const isTableTopMoreText = ref(false);
  const toploadMorePage = ref(0);
  /**表格分页---end */
  const propsButtonObj: any = ref({});
  // 拖拽配置参数
  const resizeConf = reactive({
    width: 270, // 初始宽度
    widthRange: [200, 1500] // 宽度范围
  });

  //创建文件夹参数
  const yuCreateFolderRef = ref();
  const docBtnRefsData = ref(null);
  //---------------------------------------------------------------------------------------------------------

  // 上传文件弹窗
  const uploadFileRef = ref(null);
  // 上传知识库封面
  const uploadCoverRef = ref(null);

  // 定义选中文件夹数据
  const treeFolderData = reactive({
    type: '',
    parentId: null,
    libraryId: null
  });

  // const emit: any = defineEmits(['sort-changed']);
  /**create-upload-btn组件事件--------------start */
  // 创建上传按钮点击事件
  const ocrFileRef = ref(null) // ocr组建实例
  const createUploadBtnClick = (command: any) => {
    // 新建文件夹
    if (command == 'newFolder') {
      opendialogRename('craete');
    }
    if (command == 'fileDialog') {
      tirggerFileDialog();
    }
    if (command == 'folderDialog') {
      tirggerFolderDialog();
    }
    // ocr文件处理
    if (command == 'OCRhandle') {
      // router.push('/ocr-recognitionVive')
      // window.open(`/ocr-recognitionVive?id=${tableRequestParams.value.parentId}`)
      ocrFileRef.value.open(tableRequestParams.value.parentId);
    }
  };

  // 上传方法
  const tirggerFileDialog = () => {
    treeFolderData.parentId = tableRequestParams.value.parentId;
    treeFolderData.libraryId = rowData.id;
    treeFolderData.type = configs.uploadType;
    uploadFileRef.value?.triggerFile(treeFolderData);
  };
  // 上传文件夹
  const tirggerFolderDialog = () => {
    treeFolderData.libraryId = rowData.id;
    treeFolderData.parentId = tableRequestParams.value.parentId;
    treeFolderData.type = configs.uploadType;
    uploadFileRef.value?.triggerFolder(treeFolderData);
  };
  // 搜索按钮点击事件
  const handleSelectSearch = async (val) => {
    searchInfoObj.value = val;
    let oParam = {
      // id: '3e4e2a1047854f329e96b9b5ce71b4fa',
      id: val.id,
      fileType: 'enterprise',
      sort: treeRequestParams.value.sort,
      size: tableRequestParams.value.size
    };

    ApiPerTreeNodeAll(oParam).then((res) => {
      let superiorList = [...res.data.superior];
      superiorList.shift();

      expandedKeys.value = res.data.superior.map((item) => {
        return parseInt(item.id);
      });
      treeDocumentRefs.value.setCurrentKey(expandedKeys.value[expandedKeys.value.length - 1]); //设置选中状态
      /**设置右边表格数据 */
      if (res.data.list.page > 1) {
        //判断是否是第一页,顶部加载更多按钮就不显示
        isTableTopMoreText.value = true;
      } else {
        isTableTopMoreText.value = false;
      }
      tableData.value = [];
      if (expandedKeys.value.length == 2) {
        breadList.value = [];
      } else {
        breadList.value = superiorList;
      }

      toploadMorePage.value = res.data.list.page - 1;
      tableRequestParams.value.page = res.data.list.page - 1;
      tableRequestParams.value.pageCount = res.data.list.page; //这里为什么这样写:因为初始在请求列表中判断了页数和总页数,页数要比总页数小才能发送请求
      tableRequestParams.value.parentId = expandedKeys.value[expandedKeys.value.length - 1];
      apiTreeFileSelectTreePage('refresh');
    });
  };
  // 标题栏点击事件
  const pageTitleClick = () => {
    breadRouterClick(stratBreadList.value[0]);
  };
  /**create-upload-btn组件事件--------------end */

  const filterNode = (value: any, data: any) => {
    if (!value) return true;
    return data.label.indexOf(value) !== -1;
  };
  // 获取树
  const apiFilesTreeQuery = async () => {
    treeLoading.value = true;
    await apiTreeFileSelectTree({
      parentId: rowData.id,
      // nodeType: pageType == 'self' ? 'folder' : '',
      teamId: pageType == 'team' ? route.params.teamId : '',
      ...treeRequestParams.value
    })
      .then((res: any) => {
        headNodeId.value = res.data.id;
        managementList.value = res.data.children;
        teamId.value = res.data.teamId;
        stratBreadList.value = [];
        breadList.value = [];
        stratBreadList.value.push({
          id: res.data.id,
          label: res.data.realName
        });
        // 刷新保留树节点处理--------start
        let StoExpandedKeys = sessionStorage.getItem('expandedKeys');
        let StoExpandedKeysArr = [];
        if (StoExpandedKeys) {
          StoExpandedKeysArr = JSON.parse(StoExpandedKeys);
          handleSelectSearch(StoExpandedKeysArr[StoExpandedKeysArr.length - 1]);
        } else {
          initializeTableRequest(res.data.id);
        }

        // 刷新保留树节点处理--------end
        // if (pageType == "enterprise") {
        //   //企业文件权限调用
        //   this.$store.dispatch("getEnteroriseFileRole", {
        //     params: res.data,
        //     type: "parent"
        //   });
        // }
        // initializeTableRequest(res.data.id);

        propsButtonObj.value = {};
        treeLoading.value = false;
      })
      .catch((err) => {
        treeLoading.value = false;
      });
  };
  // 获取左侧文件树---懒加载
  const loadNode = async (node: any, resolve: any) => {
    propsButtonObj.value = node;
    if (node.level == 0) {
      return resolve(node.data);
    }
    treeLoading.value = true;

    await apiTreeFileSelectTree({
      parentId: node.data.id,
      // nodeType: pageType == 'self' ? 'folder' : '',
      teamId: pageType == 'team' ? route.params.teamId : '',
      ...treeRequestParams.value
    })
      .then((res: any) => {
        breadList.value = [];
        treeLoading.value = false;
        let childrenArr = res.data.children;
        getTreeNode(treeDocumentRefs.value.getNode(node.data.id));
        // this.SET_TABLE_DATA(res.obj.children);

        if (expandedKeys.value[expandedKeys.value.length - 1] == node.data.id) {
          // tableScrollToRow(multipleTable.value, searchInfoObj.value);
          expandedKeys.value = [0];
          sessionStorage.removeItem('expandedKeys');
        }
        // if (pageType == "enterprise") {
        //   //企业文件权限调用
        //   this.$store.dispatch("getEnteroriseFileRole", {
        //     params: this.propsButtonObj.data,
        //     type: "parent"
        //   });
        // }
        // refreshNode(childrenArr[0].id);
        return resolve(childrenArr);
      })
      .catch((err) => {
        treeLoading.value = false;
      });
  };
  // 初始化分页查询右边表格接口请求数据
  const initializeTableRequest = (id: any) => {
    tableData.value = [];
    tableRequestParams.value.page = 0;
    tableRequestParams.value.pageCount = 1;
    tableRequestParams.value.parentId = id;
    apiTreeFileSelectTreePage('refresh');
  };
  // 分页查询右边表格---底部加载更多
  const apiTreeFileSelectTreePage = (type: any) => {
    if (tableRequestParams.value.page > tableRequestParams.value.pageCount - 1) {
      return false;
    }
    tableLoading.value = true;

    apieEnterpriseFilesTreeQueryPaging({
      parentId: tableRequestParams.value.parentId,
      page: tableRequestParams.value.page,
      size: tableRequestParams.value.size,
      ...treeRequestParams.value
    })
      .then((res: any) => {
        // if(this.tableData.length == 0){
        //   this.tableData = [{}]
        // }
        if (type == 'refresh') {
          tableData.value = res.data.rows;
        } else {
          tableData.value = [...tableData.value, ...res.data.rows];
        }
        previewTableDataClone.value = tableData.value; //拷贝了一份，用来还原取消排序时的表格数据
        tableRequestParams.value.page += 1;
        tableRequestParams.value.pageCount = res.data.pageSize;
        tableLoading.value = false;
      })
      .catch((err) => {
        tableLoading.value = false;
      });
  };
  // 分页查询右边表格---顶部加载更多
  const TopLoadMoreClick = () => {
    if (toploadMorePage.value <= 0) {
      toploadMorePage.value = 0;
      // this.isTableTopMoreText = false//不显示顶部加载更多
      return;
    }
    toploadMorePage.value -= 1;
    tableLoading.value = true;
    apieEnterpriseFilesTreeQueryPaging({
      parentId: tableRequestParams.value.parentId,
      page: toploadMorePage.value,
      size: tableRequestParams.value.size,
      ...treeRequestParams.value
    })
      .then((res: any) => {
        // if(this.tableData.length == 0){
        //   this.tableData = [{}]
        // }
        if (toploadMorePage.value <= 0) {
          isTableTopMoreText.value = false; //不显示顶部加载更多
        }
        tableData.value = [...res.data.rows, ...tableData.value];
        previewTableDataClone.value = tableData.value; //拷贝了一份，用来还原取消排序时的表格数据
        tableRequestParams.value.pageCount = res.data.pageSize;
        tableLoading.value = false;
      })
      .catch((err) => {
        tableLoading.value = false;
        toploadMorePage.value += 1;
      });
  };
  //面包屑导航栏
  const getTreeNode = (node: any) => {
    if (node && node.label) {
      let obj = {
        id: node.key,
        label: node.label
      };
      breadList.value.unshift(obj);
      treeDocumentRefs.value.setCurrentKey(breadList.value[breadList.value.length - 1]); //设置选中状态
      sessionStorage.setItem('expandedKeys', JSON.stringify(breadList.value));
      getTreeNode(node.parent); //递归
    }
  };
  // 单击树
  const elTreeNodeClick = (data: any, node: any) => {
    propsButtonObj.value = node;
    // treeFolderData.libraryId = node.data.libraryId;
    refreshNode(data.id);
    handleRowClick(data);
  };

  // 刷新某个树节点，重点！！！！
  const refreshNode = (key: any, type?: any) => {
    // 获取当前节点，key可以在@node-click和:load绑定函数的回调参数node用变量存储后有需要刷新的地方取node.key
    let node = treeDocumentRefs.value.getNode(key);
    //  设置未进行懒加载状态
    node.loaded = false;
    // 重新展开节点就会间接重新触发load达到刷新效果
    node.expand();
    // 刷新右边表格
    if (type != 'delete') {
      initializeTableRequest(key);
      isTableTopMoreText.value = false;
      toploadMorePage.value = 0;
    }
    //团队权限
    // this.setTeamRoleFunction(key);
  };

  //功能方法==========================================================

  /**打开创建文件夹和重名 */
  const opendialogRename = (type: any, item?: any) => {
    if (type.type != 'richText') {
      let _data = yuCreateFolderRef.value;
      _data.title = '创建文件夹';
      //重命名
      if (type == 'rename') {
        _data.form = JSON.parse(JSON.stringify(item));
        _data.title = '重命名';
      }
      _data.visibleDialog = true;
    } else {
      // richText后缀表单富文本
      // let params = {
      //   name: docBtnRefsData.value.form.rename,
      //   type: 1, // 个人0 团队1
      //   treeNodeId: tableRowArray.value[0].id,
      //   id: tableRowArray.value[0].id
      // };
      // bpmnFromsApi.apiSysFormDocUpdate(JSON.stringify(params)).then((res) => {
      //   docBtnRefsData.value.dialogRename = false;
      //   refreshDatas("更新成功");
      // });
    }
  };

  /**确定事件-创建文件夹和重命名 */
  const realNameConfirmClick = (item: any) => {
    //重命名
    let params = null;
    if (item.id) {
      if (item.type != 'richText') {
        let oParam = {
          realName: item.realName,
          id: item.id
        };
        //文件夹和文件
        treeLoading.value = true;
        apiEnterpriseFilesTreeRename(oParam)
          .then((res) => {
            if (res.code == 401) {
              proxy?.$modal.msgError(res.msg);
              return;
            }
            refreshDatas();
            proxy?.$modal.msgSuccess('修改成功');
          })
          .catch((err) => {
            treeLoading.value = false;
          });
      } else {
        //表单父文件
        // params = {
        //   name: item.realName,
        //   type: pageType == "self" ? 0 : 1, // 个人0 团队1
        //   treeNodeId: item.id,
        //   id: item.id
        // };
        // treeLoading.value = true;
        // bpmnFromsApi
        //   .apiSysFormDocUpdate(JSON.stringify(params))
        //   .then((res) => {
        //     refreshDatas();
        //     proxy.$modal.msgSuccess("修改成功");
        //   })
        //   .catch((err) => {
        //     treeLoading.value = false;
        //   });
      }
    } else {
      let params = {
        parentId: propsButtonObj.value.key || rowData.id,
        realName: item.realName,
        extend: 1
      };
      treeLoading.value = true;
      apiTreeFileSelectTreeAddFolder(params)
        .then((res: any) => {
          if (res.code == '401') {
            proxy.$modal.msgError(res.message);
            return;
          }
          if (res.code != '400') {
            refreshDatas();
          } else {
            proxy.$modal.msgError(res.message);
          }
        })
        .catch((err) => {
          treeLoading.value = false;
        });
    }
  };
  /**table 方法和样式调整 ------------  start */
  //方法--------------------------
  // 当选择项发生变化时会触发该事件
  const handleSelectionChange = (selection: any) => {
    tableRowArray.value = selection;
    tableRowArray.value.length != 0 ? (isTableHeaderBtn.value = true) : (isTableHeaderBtn.value = false);
    //多个文件判断权限表格头按钮显示
    let paramsString = {};
    if (tableRowArray.value.length >= 1) {
      if (pageType == 'team') {
        paramsString = {
          teamId: teamId.value,
          userId: userStore.userId,
          treeNodeIds: tableRowArray.value.map((item) => item.id)
        };
        // this.$store.dispatch("getUserTeamFileRoleApi", {
        //   params: paramsString
        // });
      }
      if (pageType == 'enterprise') {
        let paramsQuery = tableRowArray.value.find((item) => item.perm == 'query');
        let paramsEditor = tableRowArray.value.find((item) => item.perm == 'editor');
        if (paramsQuery) {
          // this.$store.dispatch("getEnteroriseFileRole", {
          //   params: paramsQuery
          // });
        } else if (paramsEditor) {
          // this.$store.dispatch("getEnteroriseFileRole", {
          //   params: paramsEditor
          // });
        } else {
          // this.$store.dispatch("getEnteroriseFileRole", {
          //   params: this.tableRowArray[0]
          // });
        }
      }
    }
  };
  // 双击表格的行
  const handleRowDblClick = (val: any) => {
    // 展开左边树
    if (val.type == 'folder') {
      expandedKeys.value = [];
      refreshNode(val.id);
      currentId.value = val.id;
    }
    if (val.type == 'file') {
      proxy.$yuUtils.previewSkipPage(val);
    }
    // wen----
    if (val.type == 'richText') {
      let params: any = {
        treeNodeId: val.id
      };
      if (val.libraryType == 'enterprise') {
        params.type = 2; // 个人传0，团队传1 企业传2
      } else if (val.libraryType == 'team') {
        params.type = 1;
      }

      // this.getRichText(params);
    }
  };
  // 单击表格的行选中
  const handleRowClick = (val: any) => {
    rightInfoArray.value = val;
  };
  // 右键表格行
  const rowContextmenuClick = (row: any, column: any, event: any) => {
    multipleTable.value.clearSelection(); //清除选中
    multipleTable.value.toggleRowSelection(row); //设置选中行选中状态
    multipleTable.value.setCurrentRow(row); //用于单选表格，设定某一行为选中行
    onContextMenu(event, 'self');
  };
  // 排序
  const changeTableSort = (column: any, prop: any, order: any) => {
    let freeGood = [];
    let elseFree = [];
    let fieldName = column.prop;
    let sortingType = column.order === 'ascending' ? 'Asc' : column.order === 'descending' ? 'Desc' : null;

    if (fieldName === 'realName') {
      fieldName = 'real_name';
    }
    if (fieldName === 'updateTime') {
      fieldName = 'update_time';
    }
    if (sortingType === null) {
      fieldName = 'create_time';
      sortingType = 'Desc'; // 可以指定默认的排序方式，例如降序
    }

    tableData.value.forEach((item) => {
      if (item.sort == -1) {
        freeGood.push(item);
      } else {
        elseFree.push(item);
      }
    });

    // 根据排序类型进行排序
    if (sortingType === 'Desc' || sortingType === 'Asc') {
      elseFree.sort((a, b) => {
        if (typeof a[fieldName] === 'string') {
          return sortingType === 'Desc' ? b[fieldName].localeCompare(a[fieldName]) : a[fieldName].localeCompare(b[fieldName]);
        } else if (typeof a[fieldName] === 'number') {
          return sortingType === 'Desc' ? b[fieldName] - a[fieldName] : a[fieldName] - b[fieldName];
        }
      });
    }

    // 合并不参与排序的数据和排序后的数据
    tableData.value = [...freeGood, ...elseFree];

    // 更新 treeRequestParams.sort 数组的最后一个参数
    if (sortingType) {
      treeRequestParams.value.sort.pop(); // 移除最后一个元素
      treeRequestParams.value.sort.push(`${fieldName} ${sortingType}`);
    } else {
      // 如果没有排序方式，则还原排序参数
      treeRequestParams.value.sort = ['sort Asc', 'type Desc', 'update_time Asc'];
    }
    // 刷新右边表
    refreshDatas();
    // emit('sort-changed');
    // 更新管理列表
    let folderData = tableData.value.filter((item) => item.type === 'folder');
  };
  //样式调整------------------------
  // 单元格的 style 的回调方法
  const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
    if (columnIndex === 1) {
      return `borderColor:#eee;`;
    } else {
      return `border-right:0px`;
    }
  };
  // 合并第一行
  const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
    if (rowIndex === 0) {
      return {
        rowspan: 1,
        colspan: 5 // 合并全部五列
      };
    }
  };
  //某一行改变背景色
  const tableRowClassName = ({ row, rowIndex }) => {
    if (row.sort == -1) {
      return 'table_row_topmark';
    }
  };
  //排序按钮显示方法
  const isTableHeaderBtnFunction = () => {
    if (tableRowArray.value.length == 0) {
      return 'custom';
    } else {
      return false;
    }
  };
  /**
   *  el-table滚动到表格某一行
   *  @param {object} tableElement  表格元素(this.$refs['表格ref值'])
   *  @param {Object} row   要定位的某一行数据
   * 调用实例   tableScrollToRow(this.$refs.editTable, {})
   */
  const tableScrollToRow = (tableElement: any, row: any) => {
    let rowIndex = tableData.value.findIndex((item) => item.id == row.id);
    let rowObj = tableData.value.find((item) => item.id == row.id);
    const theTableRows = tableElement.bodyWrapper.querySelectorAll('.el-table__body tbody .el-table__row');
    let scrollTop = 0;
    for (let i = 0; i < theTableRows.length; i++) {
      if (i === rowIndex) {
        break;
      }
      scrollTop += theTableRows[i].offsetHeight;
    }
    tableElement.bodyWrapper.scrollTop = scrollTop;
    tableElement.setCurrentRow(rowObj);
  };

  /**table 方法和样式调整 ------------  end */
  //点击文件获取详情信息--------------------
  const infoRefs = ref();

  const openFileDetailClick = async (row: any) => {
    infoRefs.value.getFileInfo(row);
  };
  //收藏------------------
  // const apiFilesCollectionAddCollection = (row: any) => {
  //   FilesCollection(row)
  // };
  //更多------------------
  const moreHandleCommand = (command: any, item: any) => {
    // 预览
    if (command == 'preview') {
      handleRowDblClick(item);
    }
    // 编辑
    if (command == 'edit') {
      proxy?.$yuUtils.onlineEditSkipPage(item);
    }
    // 打印
    if (command == 'print') {
    }
    // 下载
    if (command == 'download') {
      downloadFileFunc([item]);
    }
    // 作废
    if (command == 'delete') {
      //删除
      deleteFileClick([item]);
    }
    // 订阅
    if (command == 'attention') {
      menuattentionFunc(item);
    }
    // 分配权限
    if (command == 'visitor') {
      assignPermissionsRef.value.opne(item);
    }
    // 重新加入问答知识库库
    if (command == 'joinKnowledge') {
      joinQuestionAnswer(item);
    }
    // 上传问答知识库
    if (command == 'uploadkKnowledge') {
      uploadKnowledgeBase(item);
    }
  };

  //导航栏
  const breadRouterClick = (val: any) => {
    if (breadList.value.length == 0) return;
    if (breadList.value[breadList.value.length - 1].id == val.id) return;
    if (val.id == headNodeId.value) {
      apiFilesTreeQuery();
      sessionStorage.removeItem('expandedKeys');
    } else {
      refreshNode(val.id);
    }
  };

  //table-header-btn $emit事件----------------
  const tableHeaderBtn_otherClick = (str: any) => {
    // 下载
    if (str == 'download') {
      menuDownload();
    }
    //删除
    if (str == 'delete') {
      deleteFileClick(tableRowArray.value);
    }

    //取消 or 收藏
    if (str == 'collection') {
      FilesCollection(tableRowArray.value[0]);
    }
    // 详情
    if (str == 'detail') {
      infoRefs.value.getFileInfo(tableRowArray.value[0]);
    }
    // 版本
    if (str == 'history') {
      infoRefs.value.getFileInfo(tableRowArray.value[0], 'history');
    }
    // 保存到知识库模板
    if (str == 'saveAsTemplateLiabry') {
      saveAsTemplateLiabryry(tableRowArray.value);
    }
    if (str == 'joinKnowledge') {
      joinQuestionAnswer(tableRowArray.value, 'list');
    }
    if (str == 'uploadkKnowledge') {
      uploadKnowledgeBase(tableRowArray.value, 'list');
    }
  };
  const roleList = ref<any[]>([]);
  //右键菜单-----------------------------------
  const onContextMenu = (e: any, type: any) => {
    roleStore.getEnteroriseFileRole(tableRowArray.value[0]);
    roleList.value = roleStore.enterpriseMyRoleList;
    setTimeout(() => {
      //这一步是解决菜单位置偏移的问题
      const element: any = document.querySelector('.mx-menu-host');
      if (element && element.style.top == '-12px') {
        element.classList.add('mx-menu-host_yu'); //这个样式在ruyi.scss中定义
      }
    }, 100);

    const scaledPosition = ContextMenu.transformMenuPosition(e.target as HTMLElement, e.offsetX, e.offsetY);
    e.preventDefault();
    ContextMenu.showContextMenu({
      x: scaledPosition.x,
      y: scaledPosition.y,
      zIndex: 999,
      mouseScroll: true, //是否可以在菜单区域中使用鼠标滚轮来滚动长菜单
      // adjustPosition:true,//菜单将自动调整其位置，以防止溢出容器
      adjustPadding: { x: 0, y: 10 },
      customClass: 'ContextMenuClass', //自定义样式 在rouyi.scss中定义

      items: [
        {
          icon: 'icon-view iconfont-el',
          label: tableRowArray.value[0].type == 'folder' ? proxy.$t('teamDoc.rightBtnList.open') : proxy.$t('teamDoc.rightBtnList.preview'),
          // disabled: this.judgePermission("check", myFIleRoleList),
          disabled: judgePermission('check', roleList.value), //以前注释的
          onClick: () => {
            handleRowDblClick(tableRowArray.value[0]);
          }
        },
        // 编辑
        {
          icon: 'icon-edit iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.edit'),
          hidden: tableRowArray.value[0].type == 'folder',
          // disabled: this.judgePermission("update", myFIleRoleList),
          disabled: judgePermission('update', roleList.value), //以前注释的

          onClick: () => {
            proxy?.$yuUtils.onlineEditSkipPage(tableRowArray.value[0]);
          }
        },
        // 打印
        {
          icon: 'icon-printer iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.print'),
          hidden:
            tableRowArray.value[0].type == 'folder' ||
            !(
              tableRowArray.value[0].suffix == 'doc' ||
              tableRowArray.value[0].suffix == 'docx' ||
              tableRowArray.value[0].suffix == 'xls' ||
              tableRowArray.value[0].suffix == 'xlsx' ||
              tableRowArray.value[0].suffix == 'pdf'
            ),
          disabled: judgePermission("print", roleList.value),
          onClick: () => {
            menuPrintClick(tableRowArray.value[0]);
          }
        },
        // 下载
        {
          icon: 'icon-downloads1 iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.download'),
          divided: true, //是否显示分割线
          // disabled: this.judgePermission("download", myFIleRoleList),
          disabled: judgePermission('download', roleList.value), //以前注释的
          onClick: () => {
            menuDownload();
          }
        },
        // 置顶or取消置顶
        {
          icon: 'icon-top iconfont-el',
          label: tableRowArray.value[0].sort == -1 ? proxy.$t('teamDoc.rightBtnList.cancelTop') : proxy.$t('teamDoc.rightBtnList.top'),
          // disabled: this.judgePermission(pageType == "enterprise" ? "jurisdiction" : "update", myFIleRoleList),
          disabled: judgePermission('jurisdiction', roleList.value), //以前注释的
          onClick: () => {
            TopMarkClick(tableRowArray.value[0]);
          }
        },
        // 作废
        {
          icon: 'icon-delete iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.invalid'),
          // disabled: this.judgePermission("delete", myFIleRoleList),
          disabled: judgePermission('delete', roleList.value), //以前注释的
          onClick: () => {
            menuDelete();
          }
        },
        // 删除模板
        // {
        //   icon: 'icon-delete iconfont-el',
        //   label: proxy.$t('teamDoc.rightBtnList.deleteTemplate'),
        //   hidden: pageType == 'enterprise' && tableRowArray.value[0].hasOwnProperty('templateName') ? false : true,
        //   onClick: () => {
        //     // this.delMod();
        //   }
        // },
        // 重命名
        {
          icon: 'icon-key iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.rechristen'),
          divided: true, //是否显示分割线
          // disabled: this.judgePermission("update", myFIleRoleList),
          disabled: judgePermission('update', roleList.value), //以前注释的
          onClick: () => {
            menuRename();
          }
        },
        // 收藏
        {
          icon: tableRowArray.value[0].collection == 0 ? 'iconfont icon-collect' : 'iconfont icon-collect-fill',
          label: tableRowArray.value[0].collection == 0 ? proxy.$t('teamDoc.rightBtnList.collect') : proxy.$t('teamDoc.rightBtnList.cancelCollect'),
          onClick: () => {
            // 收藏 or 取消收藏
            menuCollect();
          }
        },
        // 订阅or取消订阅
        {
          icon: tableRowArray.value[0].attention == 0 ? 'iconfont icon-like' : 'iconfont icon-like-fill',
          label:
            tableRowArray.value[0].attention == 0
              ? proxy.$t('teamDoc.rightBtnList.subscription')
              : proxy.$t('teamDoc.rightBtnList.cancelSubscription'),
          onClick: () => {
            menuattention();
          }
        },
        // 分配权限
        {
          icon: 'icon-user iconfont-el',
          // label: proxy.$t('teamDoc.rightBtnList.assignPermissions'),
          label: '权限',
          //   hidden: pageType == 'self',
          // disabled: this.judgePermission("jurisdiction", myFIleRoleList),//以前注释的
          // disabled: this.menuJurisdiction(myFIleRoleList),
          disabled: judgePermission('jurisdiction', roleList.value), //以前注释的
          onClick: () => {
            allocating();
          }
        },
        // 移交文件
        // {
        //   icon: 'icon-s-custom iconfont-el',
        //   label: proxy.$t('teamDoc.rightBtnList.handOverDocuments'),
        //   // hidden: this.isShowOwner(),
        //   disabled: false,
        //   onClick: () => {
        //     // this.updateOwner();
        //   }
        // },
        // 详情
        {
          icon: 'icon-wallet iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.details'),
          divided: true, //是否显示分割线
          onClick: () => {
            openFileDetailClick(tableRowArray.value[0]);
          }
        },
        // 重新加入问答知识库
        {
          icon: 'icon-refresh-left iconfont-el',
          label: '重新加入问答知识库',
          divided: false, //是否显示分割线
          hidden: !tableRowArray.value[0].fileDatasetId,
          onClick: () => {
            // openFileDetailClick(tableRowArray.value[0]);
            joinQuestionAnswer(tableRowArray.value[0]);
          }
        },
        // 上传问答知识库
        {
          icon: 'icon-upload iconfont-el',
          label: '上传问答知识库',
          divided: false, //是否显示分割线
          // hidden: !tableRowArray.value[0].fileDatasetId,
          hidden: uploadKnowledgeBaseShow,
          onClick: () => {
            // openFileDetailClick(tableRowArray.value[0]);
            // joinQuestionAnswer(tableRowArray.value[0]);
            uploadKnowledgeBase(tableRowArray.value[0]);
          }
        },
        // 导出
        // {
        //   icon: 'icon-upload2 iconfont-el',
        //   label: '导出',
        //   hidden: tableRowArray.value[0].type != 'folder',
        //   divided: true, //是否显示分割线
        //   onClick: () => {
        //     // this.exportFun(this.tableRowArray[0]);
        //   }
        // },
        // 同步到知识库
        // {
        //   icon: 'icon-refresh iconfont-el',
        //   label: proxy.$t('teamDoc.rightBtnList.tbdzsk'),
        //   // hidden: this.isSyncKnowledgeFunc(this.tableRowArray),
        //   divided: true, //是否显示分割线
        //   onClick: () => {
        //     // this.synchronizationKnowledge(this.tableRowArray);
        //   }
        // },
        // 更多
        {
          icon: 'icon-more-outline iconfont-el',
          label: proxy.$t('teamDoc.rightBtnList.more'),
          customClass: 'ContextMenu_more_menu_btn',
          children: [
            // 归档入库
            // {
            //   icon: 'icon-upload2 iconfont-el',
            //   label: proxy.$t('teamDoc.rightBtnList.fileIntoStorage'),
            //   hidden:
            //     // pageType == 'enterprise' && proxy.$yuUtils.LicenseInfoFunc('archives:list') && tableRowArray.value[0].type != 'folder' ? false : true,
            //     pageType == 'enterprise'&& tableRowArray.value[0].type != 'folder' ? false : true,
            //   // disabled: this.judgePermission("toArchives", myFIleRoleList),
            //   onClick: () => {
            //     // this.menuPigeonhole();
            //   }
            // },
            // 加入模板
            {
              icon: 'icon-circle-plus-outline iconfont-el',
              label: proxy.$t('teamDoc.rightBtnList.joinTemplates'),
              hidden:
                !(tableRowArray.value[0].type == 'file' && ['ppt', 'excel', 'docx'].includes(tableRowArray.value[0].suffix)) ||
                pageType == 'enterprise',
              // disabled: this.judgePermission("distribute", myFIleRoleList),
              onClick: () => {},
              children: [
                // 个人模板
                {
                  label: proxy.$t('teamDoc.rightBtnList.personalTemplateLibrary'),
                  onClick: () => {
                    // this.templateLibrary();
                  }
                },
                // 公共模板库
                {
                  label: proxy.$t('teamDoc.rightBtnList.commonTemplateLibrary'),
                  onClick: () => {
                    // this.publicTemplateLibrary();
                  }
                }
              ]
            },
            // 标签文档
            {
              icon: 'icon-reading iconfont-el',
              label: proxy.$t('teamDoc.rightBtnList.tagDocuments'),
              hidden: pageType != 'enterprise',
              disabled: judgePermission('enterpriseLabel', roleList.value),
              onClick: () => {
                menuManyDimensions(tableRowArray.value[0]);
              }
            }
            // 文件水印
            // {
            //   icon: 'icon-c-scale-to-original iconfont-el',
            //   label: proxy.$t('teamDoc.rightBtnList.fileWatermarking'),
            //   hidden: pageType != 'enterprise',
            //   // disabled: this.judgePermission("watermark", myFIleRoleList),
            //   onClick: () => {
            //     // this.OpenFileWatermark(this.tableRowArray[0]);
            //   }
            // },
            // 加入培训or取消培训
            // {
            //   icon: 'icon-data-analysis iconfont-el',
            //   label:
            //     tableRowArray.value[0].toTms == 'true' ? proxy.$t('teamDoc.rightBtnList.canceTrain') : proxy.$t('teamDoc.rightBtnList.joinTrain'),
            //   // label: `加入培训资源${this.$store.state.settings.train_enable == 'true'}${pageType != "self"}${this.tableRowArray[0].type == "file"}`,
            //   // hidden: !(this.$store.state.settings.train_enable == "true" && pageType != "self" && this.tableRowArray[0].type == "file"),
            //   // disabled: this.judgePermission("jurisdiction", myFIleRoleList),
            //   onClick: () => {
            //     // this.addTrainResourceClick(this.tableRowArray[0]);
            //   }
            // },
          ]
        }
      ]
    });
  };
  const judgePermission = (str: any, list: any) => {
    return !proxy.$yuUtils.documentsPermissionFunc([str], list);
  };
  /**其他方法-------------------------------------------- */

  /**刷新表格和数节点 刷新- 操作按钮之后刷新表格和树节点 */
  const refreshDatas = (str?: any) => {
    if (str) {
      proxy?.$modal.msgSuccess(str);
    }
    if (propsButtonObj.value.key) {
      refreshNode(propsButtonObj.value.key);
    } else {
      apiFilesTreeQuery();
    }
  };
  /**icon转换 */
  const selectSvgIcons = (v: any) => {
    return proxy.$yuUtils.selectSvgIcon(v);
  };
  /****************************************************方法start */
  // 下载
  const menuDownload = () => {
    downloadFileFunc(tableRowArray.value);
  };

  // 下载方法
  const downloadFileFunc = (itemArr: any) => {
    let ids = itemArr.map((item: any) => item.id);
    proxy?.$download.downloadFile(ids, itemArr[0].libraryType);
    return;
  };

  // 调用删除
  const menuDelete = () => {
    deleteFileClick(tableRowArray.value);
  };

  // 删除方法
  const deleteFileClick = (val: any) => {
    ElMessageBox.confirm('将删除' + val.length + '条数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        let ids = val.map((item: any) => item.id);
        let oParam = {
          ids: ids.join(','),
          type: 'enterprise'
        };
        apiRecycleBinRemoveFile(oParam).then((res) => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess('删除成功 !');
            refreshDatas();
            // apiFilesTreeQuery(); //刷新页面
          }
        });
      })
      .catch(() => {});
  };

  // 保存知识库模板
  const saveAsTemplateLiabryry = (data: any) => {
    uploadCoverRef.value?.openDialog(data);
  };

  // 调用收藏 or 取消收藏
  const menuCollect = () => {
    FilesCollection(tableRowArray.value[0]);
  };

  // 收藏 or 取消收藏 方法
  const FilesCollection = (val: any) => {
    let fileType = 2;
    if (val.collection == '1') {
      let oParam = {
        treeNodeId: val.id,
        fileType: fileType
      };
      apifilesCollectionCancelCollection(oParam).then((res: any) => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess('取消收藏成功 !');
          val.collection = '0';
          refreshDatas();
          // apiFilesTreeQuery(); //刷新页面
        }
      });
    } else {
      let oParam = {
        treeNodeId: val.id,
        fileType: fileType
      };

      apiFilesCollectionAddCollection(oParam).then((res: any) => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess('收藏成功了哦~');
          val.collection = '1';
          refreshDatas();
          // apiFilesTreeQuery(); //刷新页面
        }
      });
    }
  };

  // 调用订阅 or 取消订阅
  const menuattention = () => {
    menuattentionFunc(tableRowArray.value[0]);
  };

  // 订阅 or 取消订阅
  const menuattentionFunc = (val: any) => {
    let fileType = 2;
    if (val.attention == '1') {
      let oParam = {
        treeNodeId: val.id,
        fileType: fileType
      };
      apiFileAttentionCancelAttention(oParam).then((res: any) => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess('取消订阅成功 !');
          val.attention = '0';
          refreshDatas();
          // apiFilesTreeQuery(); //刷新页面
        }
      });
    } else {
      let oParam = {
        treeNodeId: val.id,
        fileType: fileType
      };
      apiFileAttentionAddAttention(oParam).then((res: any) => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess('订阅成功了哦~');
          val.attention = '1';
          refreshDatas();
          // apiFilesTreeQuery(); //刷新页面
        }
      });
    }
  };

  // 重命名
  const menuRename = () => {
    opendialogRename('rename', tableRowArray.value[0]);
  };

  /**置顶 */
  const TopMarkClick = (val: any) => {
    let oParam = {
      ids: [val.id],
      top: val.sort == -1 ? false : true
    };
    apiEnterpriseFilesTreeTop(oParam).then((res) => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess('置顶成功 !');
        refreshDatas();
        // apiFilesTreeQuery(); //刷新页面
      }
    });
  };
  // 分配权限
  let assignPermissionsRef: any = ref(null); //分配权限弹窗实例
  const allocating = () => {
    assignPermissionsRef.value.opne(tableRowArray.value[0]);
  };

  // 标签文档

  let manyLableRef: any = ref(null); //标签文档弹窗实例
  const menuManyDimensions = (val: any) => {
    manyLableRef.value.open(val);
  };

  // 重新加入问答知识库
  const joinQuestionAnswer = async (rowData: any, type: string) => {
    let parmas: any = {
      ids: [rowData.id]
    };
    if (type == 'list') {
      parmas.ids = rowData.map((item) => item.id);
    }
    let res = await apiEnterpriseFilesTreeUpdateAiFiles(parmas);
    if (res.code == 200) {
      proxy.$modal.msgSuccess('重新加入问答知识库成功 !');
      refreshDatas();
    }
  };

  // 上传知识库显示条件
  const uploadKnowledgeBaseShow = computed(() => {
    let show: boolean = false;
    if (rowData.aiDatasetId) {
      if (tableRowArray.value[0].fileDatasetId) {
        show = true;
      } else {
        show = !['txt', 'markdown', 'pdf', 'html', 'xlsx', 'xls', 'docx', 'csv', 'md', 'htm'].includes(tableRowArray.value[0].suffix);
      }
    } else {
      show = true;
    }
    return show;
  });
  // 上传知识库
  const uploadKnowledgeBase = async (row: any, type: string) => {
    let params = {
      ids: [row.id]
    };
    if (type == 'list') {
      params.ids = row.map((item) => item.id);
    }
    let res: any = await apiEnterpriseFilesTreeToDify(params);
    if (res.code == 200) {
      proxy.$modal.msgSuccess('上传成功 !');
      refreshDatas();
    }
  };

   //打印
   const menuPrintClick = async (row) => {
    let params = {
      moduleId: row.id,
      type: 'enterprise'
    };
    let res = await apiOnlinePrint(params);
    const blobData = [res] as any[];
    const blob = new Blob(blobData, { type: 'application/pdf' });
    const blobURL = window.URL.createObjectURL(blob);
    printJS({
      type: 'pdf',
      printable: blobURL,
      documentTitle: '111', //标题
      targetStyle: '*',
      targetStyles: '*',
      scanStyles: true,
      // 默认800，设置1000是因为我窗口宽度是1000，而导致页面靠近左边，设置1000就正常居中了。
      maxWidth: '1300',
      // onPrintDialogClose:()=>{
      //     console.log(111111111111111);
      // },
      // onPdfOpen: ()=>{
      //   console.log(2222222222222222);
      // },

      //记录打印人员(暂无接口)
      onLoadingEnd: async () => {
        let params = {
          id: row.id,
          type: 'enterprise'
        };
        // let res = await collectionApi.apiOnlinePrintCallBack(params);
      }
      // onLoadingStart: function(){
      //   console.log(4444444444);
      // }
    } as any);
  };

  /****************************************************方法start */
  onMounted(() => {
    apiFilesTreeQuery();
    tableHeight.value = window.innerHeight - 98;
    window.onresize = () => {
      //浏览器窗口变动的时候
      tableHeight.value = window.innerHeight - 98;
    };
  });

  onUnmounted(() => {
    sessionStorage.removeItem('expandedKeys');
  });

  return {
    resizeConf,
    headNodeId,
    propsButtonObj,
    managementList,
    defaultProps,
    treeDocumentRefs,
    currentId,
    expandedKeys,
    yuCreateFolderRef,
    infoRefs,
    assignPermissionsRef,
    tableLoading,
    isTableTopMoreText,
    tableData,
    tableHeight,
    tableRowArray,
    isTableHeaderBtn,
    stratBreadList,
    breadList,
    multipleTable,
    createUploadBtnClick,
    handleSelectSearch,
    pageTitleClick,
    loadNode,
    filterNode,
    elTreeNodeClick,
    opendialogRename,
    realNameConfirmClick,
    apiTreeFileSelectTreePage,
    TopLoadMoreClick,
    tableRowClassName,
    isTableHeaderBtnFunction,
    handleSelectionChange,
    handleRowDblClick,
    handleRowClick,
    rowContextmenuClick,
    changeTableSort,
    selectSvgIcons,
    openFileDetailClick,
    FilesCollection,
    moreHandleCommand,
    breadRouterClick,
    tableHeaderBtn_otherClick,
    onContextMenu,
    uploadFileRef,
    refreshDatas,
    rowData,
    manyLableRef,
    uploadCoverRef,
    ocrFileRef
  };
}
